package com.wang.ddp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.ddp.dto.Result;
import com.wang.ddp.dto.UserDTO;
import com.wang.ddp.entity.Blog;
import com.wang.ddp.entity.Follow;
import com.wang.ddp.entity.ScrollResult;
import com.wang.ddp.entity.User;
import com.wang.ddp.mapper.BlogMapper;
import com.wang.ddp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.ddp.service.IUserService;
import com.wang.ddp.utils.SystemConstants;
import com.wang.ddp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private FollowServiceImpl followService;
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null){
            return Result.fail("博客不存在！");
        }
        //查询相关用户
        User user = userService.getById(blog.getUserId());
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        //查询用户是否点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //1、获取当前登录用户id
        UserDTO user = UserHolder.getUser();
        //1.1、如果用户未登录就来查看博客，就不查询是否点赞了
        if (user == null){
            return;
        }
        Long userId = user.getId();

        //2、判断当前用户是否已经点过赞
        String key = "blog:liked:"+blog.getId();
//        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result likeBlog(Long id) {
        //1、获取当前登录用户id
        Long userId = UserHolder.getUser().getId();
        //2、判断当前用户是否已经点过赞
        String key = "blog:liked:"+id;
//        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3、如果未，可以点赞
        if (score == null) {
            //3.1、数据库点赞+1
            boolean isSuccess = this.update().setSql("liked = liked + 1 ").eq("id", id).update();
            //3.2、保存用户到redis的set集合
            if (isSuccess){
                //zadd key value score  ,用时间戳做分数值来排序，从小到大排
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
//                stringRedisTemplate.opsForSet().add(key,userId.toString());
            }
        }else {
            //4、如果以点赞，则取消点赞
            //4.1、数据库点赞-1
            boolean isSuccess = this.update().setSql("liked = liked - 1 ").eq("id", id).update();

            //4.2、redis移除用户id
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
//                stringRedisTemplate.opsForSet().remove(key,userId.toString());
            }

        }
        return Result.ok();
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1、查询top5的点赞用户 zrange key 0 4
        String key = "blog:liked:"+id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //2、解析出其中的用户id
        if (top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3、查询用户信息
        //将list集合中的数据转为字符串格式并用,分割
        String idStr = StrUtil.join(",", ids);
        log.info(idStr);
        //因为mysql数据库中，用in做查询条件不会按照id括号里面的值来排序，而ORDER BY FIELD(id,1010,2)
        //就是指定按照某个字段以指定的方式排序，
        //SELECT * FROM tb_user WHERE (id IN (?,?)) ORDER BY FIELD(id,1010,2)
        List<User> users = userService.query().in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list();
        //3.1、过滤用户敏感信息，返回的是UserDTO
        List<UserDTO> userDTOS = users.stream().map((user) ->
           BeanUtil.copyProperties(user, UserDTO.class)
        ).collect(Collectors.toList());
        //4、返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("请先登录！");
        }
        Long userId = user.getId();
        blog.setUserId(userId);
        // 保存探店博文
        blog.setCreateTime(LocalDateTime.now());
        boolean isSuccess = this.save(blog);
        if (!isSuccess){
            return Result.fail("发布失败，请重试！");
        }
        log.info("{}",blog.getCreateTime());
        LocalDateTime createTime = blog.getCreateTime();
        //LocalDateTime转时间戳
        Long milliSecond = createTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
//        select * from tb_follow where follow_user_id = userid;
        List<Follow> followList = followService.query().eq("follow_user_id", userId).list();
        //feed:1----->26
        //意思是将id为26的博客推送给id为1的用户
        String prefix = "feed:";
        for (Follow follow : followList) {
            stringRedisTemplate.opsForZSet().add(prefix+follow.getUserId().toString(),blog.getId().toString(),milliSecond);
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1、获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = "feed:"+userId.toString();
        //2.查询收件箱 ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //4.解析数据：blogId,minTime(时间戳),offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        //minTime是记录最小时间戳，也是zset中的score值，因为得到的Set集合是降序，所以，最后一个元素的score值一定是最小的
        long minTime = 0;
        int count = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //4.1获取id
            blogIds.add(Long.valueOf(Objects.requireNonNull(typedTuple.getValue())));
            //4.2获取时间戳
            long time = Objects.requireNonNull(typedTuple.getScore()).longValue();
            if (minTime == time){
                count++;
            }else {
                count = 1;
                minTime = time;
            }
        }
        //根据id查询blog
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogList = this.query().in("id", blogIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogList) {
            //5.1查询blog有关的用户
            User user = userService.getById(blog.getUserId());
            blog.setIcon(user.getIcon());
            blog.setName(user.getNickName());
            //查询用户是否点赞
            isBlogLiked(blog);
        }
        //6.封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
